﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using Ubatic.Contracts.Services;
using Ubatic.ServiceFactory;
using Ubatic.Contracts.Contracts;
using Web.Framework.Mapper;

namespace Ubatic.UI.Account
{
    public partial class Registrarse : BasePage
    {
        private IUserService UserService = Factory.GetUserService();
        private IListService ListService = Factory.GetListService();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    LoadCbo();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadCbo()
        {
            var tipoDocumentoList = ListService.ObtenerTiposDocumento();
            UIHelper.LoadCbo(tipoDocumentoList, this.cboTipoDocumentoId, string.Empty);

            var dependenciasList = ListService.ObtenerDependencias();
            UIHelper.LoadCbo(dependenciasList, this.cboDependencia, string.Empty);

            this.radRoles.DataTextField = "Nombre";
            this.radRoles.DataValueField = "Id";
            this.radRoles.DataSource = ListService.ObtenerRoles();
            this.radRoles.DataBind();
        }

        protected void btnRegistrar_Click(object sender, EventArgs e)
        {
            try
            {
                UsuarioDto usuario = new UsuarioDto();

                EntityMapper.Map(this, usuario);

                usuario.Cuil = Convert.ToInt64(this.txtCuitA.Text + this.txtCuitB.Text + this.txtCuitC.Text);
                
                // Agrego los roles
                usuario.Roles = UIHelper.GetIntFromInputChkLst(this.radRoles);

                UserService.RegistrarUsuario(usuario);

                this.masterPage.ShowMessage("Se le enviará un email para confirmar su registración", WebMessageType.Notification);
                pnlMainRegistrarse.Visible = false;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}